#!/bin/bash

echo "========================================"
echo "   五子棋游戏 Protobuf 代码生成工具"
echo "========================================"
echo ""

# 获取脚本所在目录
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROTO_FILE="$SCRIPT_DIR/game.proto"

# 设置输出目录
SERVER_OUT="$SCRIPT_DIR/../server/src/main/java"
CLIENT_OUT="$SCRIPT_DIR/../client/Assets/Scripts/Proto"

echo "[1/5] 检查 protoc 是否安装..."
if ! command -v protoc &> /dev/null; then
    echo "[错误] 未找到 protoc 编译器！"
    echo ""
    echo "请先安装 protoc:"
    echo "Ubuntu/Debian: sudo apt install protobuf-compiler"
    echo "Mac: brew install protobuf"
    echo ""
    exit 1
fi
echo "[成功] protoc 已安装"
protoc --version
echo ""

echo "[2/5] 检查 proto 文件..."
if [ ! -f "$PROTO_FILE" ]; then
    echo "[错误] 找不到 proto 文件: $PROTO_FILE"
    exit 1
fi
echo "[成功] proto 文件存在: game.proto"
echo ""

echo "[3/5] 生成 Java 代码 (服务器端)..."
if [ ! -d "$SERVER_OUT" ]; then
    echo "[警告] 服务器输出目录不存在，正在创建..."
    mkdir -p "$SERVER_OUT"
fi

protoc --java_out="$SERVER_OUT" --proto_path="$SCRIPT_DIR" "$PROTO_FILE"
if [ $? -ne 0 ]; then
    echo "[错误] Java 代码生成失败！"
    exit 1
fi
echo "[成功] Java 代码已生成到: $SERVER_OUT/com/gobang/proto/"
echo ""

echo "[4/5] 生成 C# 代码 (客户端)..."
if [ ! -d "$CLIENT_OUT" ]; then
    echo "[警告] 客户端输出目录不存在，正在创建..."
    mkdir -p "$CLIENT_OUT"
fi

protoc --csharp_out="$CLIENT_OUT" --proto_path="$SCRIPT_DIR" "$PROTO_FILE"
if [ $? -ne 0 ]; then
    echo "[错误] C# 代码生成失败！"
    exit 1
fi
echo "[成功] C# 代码已生成到: $CLIENT_OUT/"
echo ""

echo "[5/5] 清理旧的 proto 文件..."
# 删除服务器旧的 proto 文件
if [ -f "$SCRIPT_DIR/../server/src/main/proto/game.proto" ]; then
    rm "$SCRIPT_DIR/../server/src/main/proto/game.proto"
    echo "[清理] 已删除服务器旧 proto 文件"
fi

# 删除客户端旧的 proto 文件
if [ -f "$CLIENT_OUT/game.proto" ]; then
    rm "$CLIENT_OUT/game.proto"
    echo "[清理] 已删除客户端旧 proto 文件"
fi
echo ""

echo "========================================"
echo "          代码生成完成！"
echo "========================================"
echo ""
echo "生成的文件:"
echo "  服务器端: $SERVER_OUT/com/gobang/proto/GameProto.java"
echo "  客户端:   $CLIENT_OUT/Game.cs"
echo ""
echo "提示:"
echo "  1. 服务器端需要重新编译项目"
echo "  2. Unity 客户端会自动检测到新文件"
echo "  3. 如有编译错误，请刷新 Unity 编辑器"
echo ""
